package org.usmile.algorithms.learn.sort;

import java.util.Arrays;

/**
 * 归并排序
 */
public class MergeSorter {
    public void sort(int[] nums) {
        if (nums == null || nums.length <= 1) {
            return;
        }

        sort(nums, 0, nums.length - 1);
    }

    private void sort(int[] nums, int left, int right) {
        if (left == right) {
            return;
        }

        int mid = left + (right - left) / 2;
        sort(nums, left, mid);
        sort(nums, mid + 1, right);

        merge(nums, left, mid, right);
    }

    private void merge(int[] nums, int left, int mid, int right) {
        int[] temp = new int[right - left + 1];
        int i = left;
        int j = mid + 1;
        int k = 0;
        while (k < temp.length) {
            if (i == mid + 1) {
                temp[k++] = nums[j++];
            } else if (j == right + 1) {
                temp[k++] = nums[i++];
            } else if (nums[i] > nums[j]) {
                temp[k++] = nums[j++];
            } else {
                temp[k++] = nums[i++];
            }
        }

        for (k = 0; k < temp.length; k++) {
            nums[left++] = temp[k];
        }
    }

    private void merge1(int[] nums, int left, int mid, int right) {
        int[] temp = new int[right - left + 1];
        int i = left;
        int j = mid + 1;
        int k = 0;

        while (i <= mid && j <= right) {
            if (nums[i] > nums[j]) {
                temp[k++] = nums[j++];
            } else {
                temp[k++] = nums[i++];
            }
        }
        while (i <= mid) {
            temp[k++] = nums[i++];
        }
        while (j <= right) {
            temp[k++] = nums[j++];
        }

        for (k = 0; k < temp.length; k++) {
            nums[left++] = temp[k];
        }
    }


    public void sort2(int[] nums) {
        if (nums == null || nums.length <= 1) {
            return;
        }

        for (int size = 1; size < nums.length; size *= 2) {
            for (int left = 0; left < nums.length - size; left += 2 * size) {
                int right = Math.min(left + 2 * size - 1, nums.length - 1);
                int mid = left + size - 1;
                merge(nums, left, mid, right);
            }
        }
    }

    public static void main(String[] args) {
        int[] nums = new int[]{1, 4, 3, 2, 10, 20, 18, 9, 7, 5, 13};
        new MergeSorter().sort2(nums);

        System.out.println(Arrays.toString(nums));
    }
}
